import React, { Component, Fragment, createRef } from 'react'
import { render } from 'react-dom'
import Swiper from 'swiper'

import getUrlParams from '../js/getUrlParams'

import { getBookSound, getBookPicture } from '../api'

import 'swiper/css/swiper.css'
import '../css/style.less'

import Top from './Top'

class App extends Component {
    constructor() {
        super()
        this.state = {
            params: {
                studentId: 0,
                pictureBookId: 0,
                soundRecordId: 0
            },
            soundList: [],
            isPlaying: false,
            isAutoPlay: true,
            currentSrc: '',
            delay: 2000
        }
        this.startTimer = null
        this.endTimer = null
        this.noAudioTimer = null
        this.swiper = null
        this.audio = createRef()
    }

    getSound = () => {
        this.setState({
            params: {
                studentId: getUrlParams('studentId'),
                pictureBookId: getUrlParams('pictureBookId'),
                soundRecordId: getUrlParams('soundRecordId')
            }
        }, async () => {
            let res = null

            if (this.state.params.soundRecordId > 0) {
                res = await getBookSound({
                    studentId: this.state.params.studentId,
                    soundRecordId: this.state.params.soundRecordId
                })
            } else {
                res = await getBookPicture({
                    studentId: this.state.params.studentId,
                    pictureBookId: this.state.params.pictureBookId
                })
            }

            this.setState({
                soundList: res.data
            })

            this.initSwiper()
            this.startPlay()
        })
    }

    autoPlay = audio => {
        if (navigator.userAgent.includes('MicroMessenger')) {
            wx.config({
                debug: false,
                appId: '',
                timestamp: 1,
                nonceStr: '',
                signature: '',
                jsApiList: []
            })
    
            wx.ready(() => {
                audio.play()
            })
        } else {
            audio.play().then(() => {
                this.setState({
                    isAutoPlay: true
                })
            }).catch(() => {
                this.setState({
                    isAutoPlay: false
                })
            })
        }
    }

    handlePlay = () => {
        this.autoPlay(this.audio.current)

        this.setState({
            isAutoPlay: true
        })
    }

    play = () => {
        let currentSrc = this.state.soundList[this.swiper.realIndex].originalsound

        if (this.state.params.soundRecordId > 0) {
            currentSrc = this.state.soundList[this.swiper.realIndex].mysoundurl
        }

        this.setState({ currentSrc })

        this.startTimer = setTimeout(() => {
            this.setState({
                isPlaying: true
            })

            this.autoPlay(this.audio.current)
        }, this.state.delay)

        if (!this.state.currentSrc) {
            this.noAudioTimer = setTimeout(() => {
                this.swiper.slideNext()
            }, 5000)

            clearTimeout(this.startTimer)
        }
    }

    startPlay = () => {
        this.play()

        this.audio.current.addEventListener('ended', () => {
            this.setState({
                isPlaying: false,
                delay: 0
            })

            this.endTimer = setTimeout(() => {
                this.swiper.slideNext()
            }, 1000)
        })

        this.swiper.on('touchEnd', () => {
            this.setState({
                delay: 1000
            })
        })

        this.swiper.on('slideChangeTransitionEnd', () => {
            this.setState({
                isPlaying: false
            })

            clearTimeout(this.startTimer)
            clearTimeout(this.noAudioTimer)

            this.play()
        })
    }

    initSwiper = () => {
        this.swiper = new Swiper('.swiper-container', {
            pagination: {
                el: '.swiper-pagination',
                type: 'fraction',
                speed: 400,
                renderFraction: (currentClass, totalClass) => {
                    return '<span class="' + currentClass + '"></span>' +
                            '/' +
                            '<span class="' + totalClass + '"></span>'
                }
            }
        })
    }

    componentDidMount() {
        this.getSound()
    }

    render() {
        const { soundList, isPlaying, isAutoPlay, currentSrc } = this.state

        return (
            <Fragment>
                <Top bg={'yellow'} />
                <div className="playing">
                    <div className="swiper-container">
                        <div className="swiper-pagination"></div>
                        <div className="swiper-wrapper">
                            {soundList.map((item, index) => (
                                <div key={index} className="swiper-slide">
                                    <div style={{background: `url(${item.innerpictureurl}) center / cover`}}></div>
                                    <p>{item.centence}</p>
                                </div>
                            ))}
                        </div>
                        <audio ref={this.audio} src={currentSrc}></audio>
                        {
                            isAutoPlay
                            ?
                            isPlaying ? <div className="voice"></div> : null
                            :
                            <div className="hand-play" onClick={this.handlePlay}></div>
                        }
                    </div>
                </div>
                <a className="free-collection2" href={`collection.html?studentId=${getUrlParams('studentId')}&pictureBookId=${getUrlParams('pictureBookId')}`}></a>
            </Fragment>
        )
    }
}

const el = document.getElementById('app')

render(
    <App />,
    el
)